import { createRouter, createWebHistory } from 'vue-router'
import { getValidToken } from '@/utils/tokenAxiosUtils'

// 定义路由组件
import UserLogin from '../views/UserLogin.vue'
import Home from '../views/Home.vue'
import BlogEdit from '@/views/BlogEdit.vue'

// blog路由组
const blogRoutes = [
    {
        path: '/edit',
        name: 'BlogEdit',
        component: BlogEdit,
        meta: { requiresAuth: true }
    },
    {
        path: '/blog/:id',
        name: 'Blog',
        component: () => import('@/views/BlogReadView.vue'),
        props: (route) => ({
            id: Number(route.params.id) || -1,
        }),
    },
    {
        path: '/blogPreview/:index',
        name: 'BlogPreview',
        component: () => import('@/views/BlogPreviewView.vue'),
        props: (route) => ({
            index: Number(route.params.index) || -1
        }),
    }
]

// user路由组
const userRoutes = [
    {
        path: '/login',
        name: 'UserLogin',
        component: UserLogin,
        meta: {
            showNavbar: false,
        }
    },
    {
        path:'/userSpace/:id',
        name: 'UserSpace',
        component: () => import('@/views/user/UserSpaceView.vue'),
        props: (route) => ({
            id: Number(route.params.id) || -1
        }),
    }
]

const router = createRouter({
    history: createWebHistory(),
    routes: [
        {
            path: '/',
            name: 'Home',
            component: Home,
        },
        ...blogRoutes,
        ...userRoutes,
    ]
})

// 优化后的路由守卫
router.beforeEach(async (to, from, next) => {
    console.log('[路由守卫] 开始处理导航',
        `\n来自: ${from.name || from.path}`,
        `\n前往: ${to.name || to.path}`);

    // 处理登录页特殊逻辑
    if (to.name === 'UserLogin') {
        console.log('[登录页] 开始验证已登录状态');
        const token = await getValidToken().catch(() => null);

        if (token) {
            window.alert('已登录用户，禁止重复登录，将跳转首页');
            console.warn('[登录拦截] 已存在有效令牌，重定向至首页');
        }

        next(token ? { name: 'Home' } : undefined);
        return;
    }

    // 处理需要认证的路由
    if (to.meta.requiresAuth) {
        console.log('[鉴权] 开始验证受保护路由', to.path);
        try {
            const token = await getValidToken();
            console.log('[令牌状态]', token ? '有效令牌存在' : '无有效令牌');

            if (token) {
                console.log('[鉴权通过] 放行路由', to.path);
                next();
            } else {
                window.alert('需要登录才能访问该页面，即将跳转登录');
                console.error('[鉴权失败] 无有效令牌', to.path);
                next({
                    name: 'UserLogin',
                    query: { redirect: to.fullPath }
                });
            }
        } catch (error) {
            window.alert('身份验证异常，请重新登录');
            console.error('[令牌刷新失败]', error);
            clearAuth();
            next({
                name: 'UserLogin',
                query: { redirect: to.fullPath }
            });
        }
        return;
    }

    console.log('[公开路由] 直接放行', to.path);
    next();
});

export default router;